<template>
  <div>
    <el-container style="height: 900px; border: 1px solid #eee">
      <!-- 顶部导航栏 -->
      <el-header style="font-size: 40px; background-color: rgb(238, 241, 246)">
        <div class="header-left">
          <span>书缘校园-校园二手书交流系统</span>
        </div>
        <div class="header-right">
          <router-link to="/mySetting">
            <el-avatar src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
          </router-link>
        </div>
      </el-header>

      <el-container>
        <!-- 侧边栏 -->
        <aside-layout></aside-layout>

        <!-- 主内容区 -->
        <el-main>
          <!-- 出租书籍表单 -->
          <el-card class="rental-form-card">
            <div slot="header" class="clearfix">
              <span>出租书籍</span>
            </div>
            <el-form :model="rentalForm" :rules="rentalRules" ref="rentalForm" label-width="100px">
              <el-form-item label="书名" prop="name">
                <el-input v-model="rentalForm.name" placeholder="请输入书名"></el-input>
              </el-form-item>
              <el-form-item label="作者" prop="author">
                <el-input v-model="rentalForm.author" placeholder="请输入作者"></el-input>
              </el-form-item>
              <el-form-item label="价格" prop="price">
                <el-input-number v-model="rentalForm.price" placeholder="请输入价格" :min="0"></el-input-number>
              </el-form-item>
              <el-form-item label="分类" prop="category">
                <el-select v-model="rentalForm.category" placeholder="请选择分类" style="width: 100%;">
                  <el-option label="小说" value="小说"></el-option>
                  <el-option label="教材" value="教材"></el-option>
                  <el-option label="其他" value="其他"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="简介" prop="intro">
                <el-input type="textarea" v-model="rentalForm.intro" placeholder="请输入书籍简介"></el-input>
              </el-form-item>
              <el-form-item label="出租时间" prop="rent_date">
                <el-date-picker v-model="rentalForm.rent_date" type="date" placeholder="选择出租日期"
                  style="width: 100%;"></el-date-picker>
              </el-form-item>
              <el-form-item label="归还时间" prop="return_date">
                <el-date-picker v-model="rentalForm.return_date" type="date" placeholder="选择归还日期"
                  style="width: 100%;"></el-date-picker>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitRentalForm('rentalForm')">提交</el-button>
                <el-button @click="resetRentalForm('rentalForm')">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>

          <!-- 已出租书籍列表 -->
          <el-card class="rented-books-card" style="margin-top: 20px;">
            <div slot="header" class="clearfix">
              <span>已出租书籍</span>
            </div>
            <el-table :data="rentedBooks"
              style="width: 100%; border-radius: 8px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);"
              :header-cell-style="{ background: '#f5f7fa', color: '#333', fontWeight: 'bold' }"
              :cell-style="{ padding: '12px 8px' }">
              <el-table-column prop="name" label="书名" width="200"></el-table-column>
              <el-table-column prop="author" label="作者" width="150"></el-table-column>
              <el-table-column prop="price" label="价格" width="120"></el-table-column>
              <el-table-column prop="category" label="分类" width="120"></el-table-column>
              <el-table-column prop="intro" label="简介" width="300"></el-table-column>
              <el-table-column prop="rent_date" label="出租时间" width="150"></el-table-column>
              <el-table-column prop="return_date" label="归还时间" width="150"></el-table-column>
              <el-table-column label="操作" width="150">
                <template slot-scope="scope">
                  <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
                  <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
              :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper" :total="totalBooks"
              style="margin-top: 20px;"></el-pagination>
          </el-card>
        </el-main>
      </el-container>
    </el-container>

    <!-- 编辑书籍弹窗 -->
    <el-dialog title="编辑书籍" :visible.sync="editDialogVisible" width="50%">
      <el-form :model="editForm" :rules="rentalRules" ref="editForm" label-width="100px">
        <el-form-item label="书名" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入书名"></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="editForm.author" placeholder="请输入作者"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="editForm.price" placeholder="请输入价格" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="editForm.category" placeholder="请选择分类" style="width: 100%;">
            <el-option label="小说" value="小说"></el-option>
            <el-option label="教材" value="教材"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <el-input type="textarea" v-model="editForm.intro" placeholder="请输入书籍简介"></el-input>
        </el-form-item>
        <el-form-item label="出租时间" prop="rent_date">
          <el-date-picker v-model="editForm.rent_date" type="date" placeholder="选择出租日期"
            style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="归还时间" prop="return_date">
          <el-date-picker v-model="editForm.return_date" type="date" placeholder="选择归还日期"
            style="width: 100%;"></el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEditForm">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import AsideLayout from '../../layout/AsideLayout.vue';
import axios from 'axios'; // 引入 axios

export default {
  components: { AsideLayout },
  data() {
    return {
      rentalForm: {
        name: '',
        author: '',
        price: 0,
        category: '',
        intro: '',
        rent_date: '', // 出租时间
        return_date: '' // 归还时间
      },
      rentalRules: {
        name: [
          { required: true, message: '请输入书名', trigger: 'blur' }
        ],
        author: [
          { required: true, message: '请输入作者', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入价格', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ],
        intro: [
          { required: true, message: '请输入书籍简介', trigger: 'blur' }
        ],
        rent_date: [
          { required: true, message: '请选择出租时间', trigger: 'change' }
        ]
      },
      rentedBooks: [], // 从 API 获取的出租书籍数据
      currentPage: 1,
      pageSize: 10,
      totalBooks: 0, // 从 API 获取的总书籍数量
      fileList: [],
      editDialogVisible: false, // 编辑弹窗的显示状态
      editForm: {
        id: null, // 当前编辑的书籍 ID
        name: '',
        author: '',
        price: 0,
        category: '',
        intro: '',
        rent_date: '',
        return_date: ''
      }
    };
  },
  methods: {
    // 提交出租书籍表单
    submitRentalForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            // 将日期格式转换为 YYYY-MM-DD
            const formatDate = (date) => {
              if (!date) return null;
              const d = new Date(date);
              const year = d.getFullYear();
              const month = String(d.getMonth() + 1).padStart(2, '0');
              const day = String(d.getDate()).padStart(2, '0');
              return `${year}-${month}-${day}`;
            };

            // 转换出租时间和归还时间
            this.rentalForm.rent_date = formatDate(this.rentalForm.rent_date);
            this.rentalForm.return_date = formatDate(this.rentalForm.return_date);

            // 提交表单数据到后端
            await axios.post('http://localhost:3000/api/rented-books', this.rentalForm);
            this.$message.success('书籍出租成功');
            this.resetRentalForm(formName);
            this.fetchRentedBooks(); // 刷新列表
          } catch (error) {
            this.$message.error('提交失败，请重试');
          }
        } else {
          this.$message.error('表单验证失败');
          return false;
        }
      });
    },
    // 重置出租书籍表单
    resetRentalForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 编辑书籍
    handleEdit(row) {
      // 打开编辑弹窗并填充数据
      this.editForm = { ...row };
      this.editDialogVisible = true;
    },
    // 保存编辑后的书籍信息
    async saveEditForm() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          try {
            // 将日期格式转换为 YYYY-MM-DD
            const formatDate = (date) => {
              if (!date) return null;
              const d = new Date(date);
              const year = d.getFullYear();
              const month = String(d.getMonth() + 1).padStart(2, '0');
              const day = String(d.getDate()).padStart(2, '0');
              return `${year}-${month}-${day}`;
            };

            // 转换出租时间和归还时间
            this.editForm.rent_date = formatDate(this.editForm.rent_date);
            this.editForm.return_date = formatDate(this.editForm.return_date);

            // 提交编辑后的数据到后端
            await axios.put(`http://localhost:3000/api/rented-books/${this.editForm.id}`, this.editForm);
            this.$message.success('书籍信息更新成功');
            this.editDialogVisible = false; // 关闭弹窗
            this.fetchRentedBooks(); // 刷新列表
          } catch (error) {
            this.$message.error('更新失败，请重试');
          }
        } else {
          this.$message.error('表单验证失败');
          return false;
        }
      });
    },
    // 删除书籍
    async handleDelete(row) {
      try {
        await axios.delete(`http://localhost:3000/api/rented-books/${row.id}`);
        this.$message.success('书籍删除成功');
        this.fetchRentedBooks(); // 刷新列表
      } catch (error) {
        this.$message.error('删除失败，请重试');
      }
    },
    // 分页大小改变
    handleSizeChange(size) {
      this.pageSize = size;
      this.fetchRentedBooks();
    },
    // 当前页改变
    handleCurrentChange(page) {
      this.currentPage = page;
      this.fetchRentedBooks();
    },
    // 预览文件
    handlePreview(file) {
      console.log('预览文件：', file);
    },
    // 移除文件
    handleRemove(file, fileList) {
      console.log('移除文件：', file, fileList);
    },
    // 获取出租书籍数据
    async fetchRentedBooks() {
      try {
        const response = await axios.get('http://localhost:3000/api/rented-books', {
          params: {
            page: this.currentPage,
            size: this.pageSize
          }
        });
        this.rentedBooks = response.data.rentedBooks;
        this.totalBooks = response.data.total;
      } catch (error) {
        this.$message.error('获取数据失败，请重试');
      }
    }
  },
  mounted() {
    this.fetchRentedBooks(); // 页面加载时获取数据
  }
};
</script>

<style scoped>
.el-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  font-weight: bold;
}

.header-right {
  display: flex;
  align-items: center;
}

.header-right a {
  margin-right: 20px;
  color: #333;
  text-decoration: none;
}

.rental-form-card,
.rented-books-card {
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.el-table {
  margin-top: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.el-table__header th {
  background-color: #f5f7fa;
  color: #333;
  font-weight: bold;
}

.el-table__body tr:hover {
  background-color: #f0f9eb;
}

.el-pagination {
  margin-top: 20px;
}
</style>